//
//  VideoViewController.m
//  SuperNews
//
//  Created by dllo on 16/1/14.
//  Copyright © 2016年 qiang. All rights reserved.
//

#import "VideoViewController.h"
#import "VideoPageModel.h"
#import "VideoTableViewCell.h"
#import "VideoClassfilyViewController.h"



@interface VideoViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSMutableArray *videoArray;
@property (nonatomic, strong) UIButton *btn;
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, strong) AVPlayerViewController *player;
@property (nonatomic , assign) int currtRow;

@end

@implementation VideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self createSubviews];
    [self setupRefreshView];
}
- (void)createSubviews
{
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 100) style:UITableViewStylePlain];
    self.tableview.backgroundColor = [UIColor clearColor];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    [self.view addSubview:self.tableview];
    
    UIView *view = [[UIView alloc]init];
    view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH * 0.25);
    self.tableview.tableHeaderView = view;
    NSArray *array = @[@"奇葩",@"萌物",@"美女",@"精品"];
    NSArray *images = @[[UIImage imageNamed:@"qipa"],
                        [UIImage imageNamed:@"mengchong"],
                        [UIImage imageNamed:@"meinv"],
                        [UIImage imageNamed:@"jingpin"]
                        ];
    
    for (int index = 0; index < 4; index++) {
        UIButton *btn = [[UIButton alloc]init];
        btn.backgroundColor = [UIColor whiteColor];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        CGFloat btnW = SCREEN_WIDTH/4;
        CGFloat btnH = view.frame.size.height - 2;
        CGFloat btnX = btnW * index - 1;
        CGFloat btnY = 0;
        btn.frame = CGRectMake(btnX + 5, btnY, btnW, btnH);
        [btn setImage:images[index] forState:UIControlStateNormal];
        [btn setTitle:array[index] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
        [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        btn.tag = 5000 + index;
        [view addSubview:btn];
        self.btn = btn;
    }
    for (int i = 1; i < 4; i++) {
        UIView *lineView = [[UIView alloc]init];
        lineView.backgroundColor = [UIColor colorWithRed:0.942 green:0.901 blue:0.957 alpha:1.000];
        CGFloat lineW = 1;
        CGFloat lineH = self.btn.frame.size.height;
        CGFloat lineX = self.btn.frame.size.width * i;
        CGFloat lineY = self.btn.frame.origin.y;
        lineView.frame = CGRectMake(lineX, lineY, lineW, lineH);
        [view addSubview:lineView];
    }
    
    UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(0, view.frame.size.height - 8, SCREEN_WIDTH, 6)];
    lineV.backgroundColor = [UIColor colorWithRed:0.743 green:0.799 blue:0.779 alpha:1.000];
    [view addSubview:lineV];

}

-(void)setupRefreshView
{
    //1.下拉刷新
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [self.tableview.mj_header beginRefreshing];
    //2.上拉刷新
    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

- (void)loadNewData
{
    self.count = 0;
    [self getData];
 
}

- (void)loadMoreData
{
    [self getData];
}



- (void)getData
{
    NSString *url = [NSString stringWithFormat:@"http://c.m.163.com/nc/video/home/%ld-10.html",self.count];
    [AFNetTool getNetWithURL:url body:nil headFile:nil responseStyle:YZQJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if (0 == self.videoArray.count) {
            self.videoArray = [VideoPageModel baseModelWithArr:responseObject[@"videoList"]];
        } else {
            
            for (NSMutableDictionary *dic in responseObject[@"videoList"]) {
                VideoPageModel *video = [VideoPageModel baseModelWithDic:dic];
                [self.videoArray addObject:video];
            }
        }
        self.count += 10;
        // 刷新表格
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_header endRefreshing];
        [self.tableview reloadData];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
    }];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoPageModel *videodata = self.videoArray[indexPath.row];

    if (self.player) {
        [self.player.view removeFromSuperview];
    }
    self.currtRow = (int)indexPath.row;
    // 创建播放器对象
    AVPlayerItem *playItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:videodata.mp4_url]];
    self.player = [[AVPlayerViewController alloc] init];
    AVPlayer *py = [AVPlayer playerWithPlayerItem:playItem];
    self.player.player = py;
    // 添加播放器界面到控制器的view上面
    self.player.view.frame = CGRectMake(10, indexPath.row * 300 + 153 * SMALLSCREEN_HEIGHT, SCREEN_WIDTH - 20, 200);
    [self.tableview addSubview:self.player.view];
    
    // 监听播放器
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieDidFinish) name:AVPlayerItemDidPlayToEndTimeNotification object:playItem];
    [py play];
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.videoArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoTableViewCell *cell = [VideoTableViewCell cellWithTableView:tableView];
    cell.videodata = self.videoArray[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 300;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 从锚点位置出发，逆时针绕 Y 和 Z 坐标轴旋转90度
    CATransform3D transform3D = CATransform3DMakeRotation(M_PI_2, 0.0, 1.0, 1.0);
    
    // 定义 cell 的初始状态
    cell.alpha = 0.0;
    cell.layer.transform = transform3D;
    cell.layer.anchorPoint = CGPointMake(0.0, 0.5); // 设置锚点位置；默认为中心点(0.5, 0.5)
    
    [UIView animateWithDuration:0.5 animations:^{
        cell.alpha = 1.0;
        cell.layer.transform = CATransform3DIdentity;
        CGRect rect = cell.frame;
        rect.origin.x = 0.0;
        cell.frame = rect;
    }];
}


- (void)btnClick:(UIButton *)btn
{
    NSArray *arr = @[@"VAP4BFE3U",
                     @"VAP4BFR16",
                     @"VAP4BG6DL",
                     @"VAP4BGTVD"];
    for (int i = 0; i < 4; i++) {
        if (btn.tag == 5000 + i) {
            VideoClassfilyViewController *classVC = [[VideoClassfilyViewController alloc]init];
            classVC.url = arr[i];
            classVC.title = btn.titleLabel.text;
            [self.navigationController pushViewController:classVC animated:YES];
        }
    }
}
- (void)movieDidFinish
{
    self.player.showsPlaybackControls = NO;
    UIView *vc = [[UIView alloc]initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH - 40, self.player.view.frame.size.height)];
    UILabel *l =[[UILabel alloc] initWithFrame:CGRectMake(10, 80, SCREEN_WIDTH - 40, 40)];
    l.text = @"播放完毕";
    l.font = [UIFont boldSystemFontOfSize:20];
    l.textColor = [UIColor whiteColor];
    l.textAlignment = NSTextAlignmentCenter;
    [vc addSubview:l];
    vc.backgroundColor = [UIColor blackColor];
    [self.player.view addSubview:vc];
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if (self.player) {
        [self.player.player pause];
        [self.player.view removeFromSuperview];
        self.player = nil;
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
